import 'dart:async';

import 'package:fixnum/fixnum.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:math';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:jtlf/http/dio_utils.dart';
import 'package:jtlf/proto/user/user.pb.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({super.key});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final _formKey = GlobalKey<FormState>();
  final _accountController = TextEditingController();
  final _phoneController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _tenantIdController = TextEditingController();
  final _captchaController = TextEditingController();

  bool _agreeProtocol = false;
  bool _obscurePassword = true;
  bool _isLoading = false;
  String _captchaUrl = 'https://picsum.photos/200/80?random='; // 替换实际验证码接口
  int _countdown = 0;
  Timer? _timer;

  // 密码强度等级
  PasswordStrength _passwordStrength = PasswordStrength.weak;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('新用户注册')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildTenantIdInput(),
              const SizedBox(height: 15), // 分割符，15个像素的高度
              _buildAccountInput(),
              const SizedBox(height: 15),
              _buildPhoneInput(),
              const SizedBox(height: 15),
              _buildEmailInput(),
              const SizedBox(height: 15),
              _buildPasswordInput(),
              const SizedBox(height: 15),
              _buildProtocolCheckbox(),
              const SizedBox(height: 25),
              _buildRegisterButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTenantIdInput() {
    return TextFormField(
      controller: _tenantIdController,
      keyboardType: TextInputType.text,
      // inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      decoration: const InputDecoration(
        labelText: '机构代码',
        prefixIcon: Icon(Icons.house),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) return '请输入机构代码';
        // if (value.length != 11) return '手机号格式不正确';
        return null;
      },
    );
  }

  Widget _buildAccountInput() {
    return TextFormField(
      controller: _accountController,
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(
        labelText: '账号',
        prefixIcon: Icon(Icons.account_box),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) return '请输入账号';
        // if (value.length != 11) return '手机号格式不正确';
        return null;
      },
    );
  }

  Widget _buildPhoneInput() {
    return TextFormField(
      controller: _phoneController,
      keyboardType: TextInputType.phone,
      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      decoration: const InputDecoration(
        labelText: '手机号',
        prefixIcon: Icon(Icons.phone_android),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) return '请输入手机号';
        if (value.length != 11) return '手机号格式不正确';
        return null;
      },
    );
  }

  Widget _buildEmailInput() {
    return TextFormField(
      controller: _emailController,
      keyboardType: TextInputType.emailAddress,
      // inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      decoration: const InputDecoration(
        labelText: '电子邮箱',
        prefixIcon: Icon(Icons.email_outlined),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) return '请输入电子邮箱';
        if (value.indexOf('@') <= 0) return '邮箱格式不正确';
        return null;
      },
    );
  }

  Widget _buildCaptchaRow() {
    return Row(
      children: [
        Expanded(
          child: TextFormField(
            controller: _captchaController,
            decoration: InputDecoration(
              labelText: '图形验证码',
              prefixIcon: const Icon(Icons.verified),
              suffixIcon: IconButton(
                icon: const Icon(Icons.refresh),
                onPressed: _refreshCaptcha,
              ),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) return '请输入验证码';
              return null;
            },
          ),
        ),
        const SizedBox(width: 10),
        CachedNetworkImage(
          imageUrl: _captchaUrl + Random().nextInt(100).toString(),
          width: 100,
          height: 40,
          errorWidget: (context, url, error) => const Icon(Icons.error),
        ),
      ],
    );
  }

  Widget _buildPasswordInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextFormField(
          controller: _passwordController,
          obscureText: _obscurePassword,
          onChanged: (value) => _checkPasswordStrength(value),
          decoration: InputDecoration(
            labelText: '设置密码',
            prefixIcon: const Icon(Icons.lock),
            suffixIcon: IconButton(
              icon: Icon(_obscurePassword ? Icons.visibility : Icons.visibility_off),
              onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
            ),
          ),
          validator: (value) {
            if (value == null || value.isEmpty) return '请输入密码';
            if (value.length < 6) return '密码至少6位';
            return null;
          },
        ),
        const SizedBox(height: 8),
        _buildPasswordStrengthIndicator(),
      ],
    );
  }

  Widget _buildPasswordStrengthIndicator() {
    Color color;
    String text;
    switch (_passwordStrength) {
      case PasswordStrength.strong:
        color = Colors.green;
        text = '强';
        break;
      case PasswordStrength.medium:
        color = Colors.orange;
        text = '中';
        break;
      case PasswordStrength.weak:
        color = Colors.red;
        text = '弱';
        break;
    }

    return Row(
      children: [
        AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          width: 80,
          height: 4,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        const SizedBox(width: 10),
        Text(text, style: TextStyle(color: color)),
      ],
    );
  }

  Widget _buildTextWidget(String text) {
    return Baseline(
      baseline: 30, // 设置基线位置
      baselineType: TextBaseline.alphabetic,
      child: Text(text),
    );
  }

  Widget _buildProtocolCheckbox() {
    return Row(
      children: [
        Checkbox(
          value: _agreeProtocol,
          onChanged: (value) => setState(() => _agreeProtocol = value!),
        ),
        Expanded(
          child: Wrap(
            crossAxisAlignment: WrapCrossAlignment.start, // 基线对齐
            // textBaseline: TextBaseline.alphabetic, // 设置基线类型
            children: [
              _buildTextWidget('已阅读并同意'),
              TextButton(
                onPressed: _showUserProtocol,
                child: const Text('《用户协议》'),
                style: TextButton.styleFrom(
                  padding: EdgeInsets.zero,
                  minimumSize: Size.zero,
                ),
              ),
              _buildTextWidget('和'),
              TextButton(
                onPressed: _showPrivacyPolicy,
                child: const Text('《隐私政策》'),
                style: TextButton.styleFrom(
                  padding: EdgeInsets.zero,
                  minimumSize: Size.zero,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildRegisterButton() {
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          padding: const EdgeInsets.symmetric(vertical: 16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
        onPressed: _isLoading ? null : _handleRegister,
        child: _isLoading
            ? const SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            color: Colors.white,
          ),
        )
            : const Text('立即注册'),
      ),
    );
  }

  void _checkPasswordStrength(String password) {
    setState(() {
      final hasUppercase = password.contains(RegExp(r'[A-Z]'));
      final hasDigits = password.contains(RegExp(r'[0-9]'));
      final hasSpecial = password.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]'));

      int strength = 0;
      if (password.length >= 6) strength++;
      if (hasUppercase) strength++;
      if (hasDigits) strength++;
      if (hasSpecial) strength++;

      if (strength < 2) {
        _passwordStrength = PasswordStrength.weak;
      } else if (strength < 4) {
        _passwordStrength = PasswordStrength.medium;
      } else {
        _passwordStrength = PasswordStrength.strong;
      }
    });
  }

  void _refreshCaptcha() {
    setState(() {
      _captchaUrl = 'https://picsum.photos/200/80?random=${Random().nextInt(100)}';
    });
  }

  // 注册逻辑处理
  Future<void> _handleRegister() async {
    if (!_formKey.currentState!.validate()) return;
    if (!_agreeProtocol) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先同意用户协议和隐私政策')),
      );
      return;
    }

    setState(() => _isLoading = true);

    try {
      User user = User.create();
      user.tenantId = _tenantIdController.text;
      user.password = _passwordController.text;
      user.mobile = _phoneController.text;
      user.account = _accountController.text;
      user.email = _emailController.text;

      final Uint8List body = user.writeToBuffer();

      DioUtils dioUtils = DioUtils();

      final res = await dioUtils.post('/user/register', data: body);
      UserReply reply = UserReply.fromBuffer(res.data);
      int code = reply.code;
      if (code == 1) {
        _showSuccessDialog();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(reply.message ?? '注册失败')),
        );
      }

      // final response = await http.post(
      //   Uri.parse('https://api.example.com/register'),
      //   body: {
      //     'phone': _phoneController.text,
      //     'password': _passwordController.text,
      //     'captcha': _captchaController.text,
      //   },
      // );
      //
      // final result = json.decode(response.body);
      // if (response.statusCode == 200) {
      //   _showSuccessDialog();
      // } else {
      //   ScaffoldMessenger.of(context).showSnackBar(
      //     SnackBar(content: Text(result['message'] ?? '注册失败')),
      //   );
      // }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('网络连接失败，请稍后重试')),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // dio请求的例子
  void _fetchData() async {
    final http = DioUtils();

    try {
      // GET 请求示例
      final response = await http.get('/users/me');
      if (kDebugMode) {
        print('响应数据: ${response.data}');
      }

      // POST 请求示例
      await http.post('/posts', data: {
        'title': 'Flutter HTTP Demo',
        'content': 'Dio interceptor implementation'
      });
    } catch (e) {
      print('请求失败: $e');
    }
  }

  void _showUserProtocol() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('用户协议'),
        content: const SingleChildScrollView(
          child: Text('...协议内容...'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _showPrivacyPolicy() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('隐私政策'),
        content: const SingleChildScrollView(
          child: Text('...隐私政策内容...'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _showSuccessDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('注册成功'),
        content: const Text('请前往邮箱完成账号激活'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  // void _checkPasswordStrength(String password) {
  //   final rules = [
  //     RegExp(r'[A-Z]'),    // 大写字母
  //     RegExp(r'[a-z]'),    // 小写字母
  //     RegExp(r'[0-9]'),    // 数字
  //     RegExp(r'[\W_]'),    // 特殊字符
  //   ];
  //
  //   int strength = password.length >= 8 ? 1 : 0;
  //   strength += rules.where((rule) => rule.hasMatch(password)).length;
  //
  //   setState(() {
  //     if (strength < 3) {
  //       _passwordStrength = PasswordStrength.weak;
  //     } else if (strength < 5) {
  //       _passwordStrength = PasswordStrength.medium;
  //     } else {
  //       _passwordStrength = PasswordStrength.strong;
  //     }
  //   });
  // }

}

enum PasswordStrength { weak, medium, strong }
